package com.funo.ehealth.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.funo.ehealth.DB.DbcpConnectionPool;

/** 
 * 数据库工具类
 * 
 * @version V1.1
 * @author zhangguangying
 * @date 2012-11-16
 */
public class DBUtil {
	
	/**
	 * DBUtil日志记录器
	 */
	private static final Log log = LogFactory.getLog(DBUtil.class);

	/**
	 * 取得数据库连接
	 * @return Connection
	 */
	public static Connection getConnection(){
		return  DbcpConnectionPool.getInstance().getConnection();
	}
	
	/**
	 * 取得statement
	 * @param conn 数据库连接
	 * @return Statement
	 */
	public static Statement getStatement(Connection conn){
		Statement stmt = null;
		try {
			stmt = conn.createStatement();
		} catch (SQLException e) {
			log.error("创建statement异常",e);
		}
		return stmt;
	}
	
	/**
	 * 取得preparestatement
	 * @param conn 数据库连接
	 * @param sql sql语句
	 * @return PreparedStatement
	 */
	public static PreparedStatement getPreparedStatement(Connection conn,String sql){
		PreparedStatement pstmt = null;
		try {
			pstmt = conn.prepareStatement(sql);
		} catch (SQLException e) {
			log.error("创建preparedStatement异常",e);
		}
		return pstmt;
	}
	
	/**
	 * 释放statement连接、resultset连接、数据库连接
	 * @param conn 数据库连接
	 * @param stmt 数据库Statement
	 * @param res 数据库ResultSet
	 */
	public static void closeAll(Connection conn,Statement stmt,ResultSet res){
		//释放resultSet对象
		if(res != null){
			try {
				res.close();
				res = null;
			} catch (SQLException e) {
				log.error("关闭resultSet异常",e);
			}
		}
		
		//释放statement对象
		if(stmt != null){
			try {
				stmt.close();
				stmt = null;
			} catch (SQLException e) {
				log.error("关闭statement异常",e);
			}
		}
		
		//将connection对象放回连接池中
		DbcpConnectionPool.getInstance().release(conn);
	}
	
}
